package DAO;

import entity.db.CitationTextDB;
import entity.db.KnowledgeFlowDB;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author ：hzs
 * @date ：Created in 2021/1/20 21:07
 * @description：
 * @modified By：
 * @version: $
 */
public class TextDAO extends BaseDAO {

    public List<CitationTextDB> getAllCitationText() {
        String sql = "SELECT id, citation FROM citation_text";
        List<List<Object>> lists = executeReadSql(sql);
        List<CitationTextDB> result = new ArrayList<>();
        for (List<Object> list : lists) {
            CitationTextDB citationTextDB = new CitationTextDB();
            citationTextDB.setId((int)list.get(0));
            citationTextDB.setCitation((String)list.get(1));
            result.add(citationTextDB);
        }
        return result;
    }

    public List<CitationTextDB> getCitationTextNotInKnowledgeFlowTable() {
        String sql = "SELECT t1.`id`, t1.`citation` FROM citation_text AS t1 WHERE t1.`id` NOT IN (\n" +
                "SELECT citation_id AS id FROM knowledge_flow )";
        List<List<Object>> lists = executeReadSql(sql);
        List<CitationTextDB> result = new ArrayList<>();
        for (List<Object> list : lists) {
            CitationTextDB citationTextDB = new CitationTextDB();
            citationTextDB.setId((int)list.get(0));
            citationTextDB.setCitation((String)list.get(1));
            result.add(citationTextDB);
        }
        return result;
    }

    public List<List<Object>> getKnowledgeFlowNotInKFContent() {
        String sql = "SELECT t1.`id`, t1.`citation_id`, t1.`noun_phrase`, t2.`target`, t2.`citation_index`, t2.`citation` " +
                "FROM knowledge_flow t1, citation_text t2\n" +
                "WHERE t1.`citation_id` = t2.`id` AND t1.`id` NOT IN (SELECT kf_id AS id FROM kf_content)"
                + "and t2.`source` = 2690  AND t2.`target` = 1882   "
                ;
        List<List<Object>> lists = executeReadSql(sql);
        return lists;
    }

    public boolean batchInsertKnowledgeFlow(List<KnowledgeFlowDB> knowledgeFlowDBList) {
        StringBuilder sql = new StringBuilder("INSERT INTO `knowledge_flow` (citation_id, noun_phrase, distribution) VALUE");
        String format = "(%s, '%s', %s)";
        Iterator<KnowledgeFlowDB> iterator = knowledgeFlowDBList.iterator();
        while (iterator.hasNext()) {
            KnowledgeFlowDB next = iterator.next();
            sql.append(String.format(format
                    ,next.getCitationId()
                    ,next.getNounPhrase()
                    ,next.getDistribution()
            ));
            if (iterator.hasNext()) {
                sql.append(",");
            }
        }
        return executeWriteSql(sql.toString());
    }

    public static void main(String[] args) {
        new TextDAO().getAllCitationText();
    }

}
